#!/usr/bin/env python

import os
import sys
import optparse

try:
    import wxversion
    wxversion.select(('3.0', '2.9', '2.8'))
except ImportError:
    pass
except wxversion.VersionError:
    pass

try:
    import psyco
    psyco.full()
except ImportError:
    pass

opts = optparse.OptionParser(usage='%s [OPTIONS] [files ...]' % sys.argv[0])
group = opts.add_option_group('File Options')
group.add_option('-f', '--file',
                 dest='files', action='append', metavar='FILE',
                 help='Specify the file to open')
group.add_option('-i', '--index',
                 dest='index', action='append',
                 help='Specify the file index in Recent Menu top open')
group = opts.add_option_group('Debug Options')
group.add_option('-d', '--developer',
                 dest='developer', action='store_true',
                 help='Enable devloper method')
group.add_option('-V', '--verbose',
                 dest='verbose', action='store',
                 help='Set the debug verbose level')
group.add_option('-v', '--version',
                 dest='version', action='store_true',
                 help='Show the application version')


def main():
    # add the access to internal paths
    home = os.path.dirname(sys.argv[0])
    if not home:
        home = os.getcwd()

    home = os.path.realpath(home)
    sys.path.append(os.path.join(home, 'anafile'))

    import anafile.ab_config as ac
    import anafile.ab_info as ab_info
    import anafile.ab_ids as ai
    import anafile.ab_main as ab_main

    import anafile.ab_platform as ab_platform
    import anafile.ab_utils as utils

    plat = ab_platform.Platform.getInstance()
    appdata = plat.getDataDirectory()
    # global variable for Config object
    if utils.withConsole(sys.argv[0]) or \
            not utils.testDirectoryWriteable(appdata):
        inipath = home
    else:
        inipath = appdata

    cf = ac.Config(os.path.join(inipath, 'config.ini'))

    opt, args = opts.parse_args(sys.argv[1:])
    if opt.developer:
        cf.writeKey(ai.CfgParaDeveloperMethod, True, persist=False)
    if opt.verbose:
        try:
            cf.writeKey(ai.CfgParaVerbose, int(opt.verbose), persist=False)
        except (TypeError, ValueError):
            print "'verbose=%s' isn't a legal integer" % opt.verbose
            sys.exit(1)

    if opt.version:
        print "\n%s, %s  %s" % (ab_info.getApplicationName(),
                                ab_info.getApplitionCopyright(),
                                ab_info.getApplicationVersionString())
        sys.exit(0)

    if len(args):
        if not opt.files:
            opt.files = list()

        opt.files.extend(args)

    while ab_main.main(home, cf, opt.files, opt.index):
        pass

    cf.flush()

if __name__ == '__main__':
    sys.exit(main())
